const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const { v4: uuidv4 } = require('uuid');
const moment = require('moment');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(helmet());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 限流
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15分钟
    max: 100, // 限制每个IP 100次请求
    message: '请求过于频繁，请稍后再试'
});
app.use('/api', limiter);

// 数据库初始化
const db = new sqlite3.Database('./database.db');

db.serialize(() => {
    // 创建卡密表
    db.run(`CREATE TABLE IF NOT EXISTS card_keys (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        card_key TEXT UNIQUE NOT NULL,
        permission_level INTEGER DEFAULT 1,
        expires_at INTEGER NOT NULL,
        is_used BOOLEAN DEFAULT FALSE,
        used_by TEXT,
        used_at INTEGER,
        created_at INTEGER DEFAULT (strftime('%s', 'now'))
    )`);

    // 创建使用记录表
    db.run(`CREATE TABLE IF NOT EXISTS usage_logs (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        card_key TEXT NOT NULL,
        device_id TEXT NOT NULL,
        action TEXT NOT NULL,
        timestamp INTEGER DEFAULT (strftime('%s', 'now'))
    )`);

    // 插入测试卡密
    const testCards = [
        { key: 'TEST-2024-001', level: 1, days: 30 },
        { key: 'TEST-2024-002', level: 2, days: 90 },
        { key: 'TEST-2024-003', level: 3, days: 365 }
    ];

    testCards.forEach(card => {
        const expiresAt = moment().add(card.days, 'days').unix();
        db.run(
            'INSERT OR IGNORE INTO card_keys (card_key, permission_level, expires_at) VALUES (?, ?, ?)',
            [card.key, card.level, expiresAt]
        );
    });
});

// API路由
app.post('/api/verifyCard', (req, res) => {
    const { cardKey, deviceId } = req.body;
    
    if (!cardKey || !deviceId) {
        return res.status(400).json({
            success: false,
            message: '缺少必要参数'
        });
    }

    const query = `
        SELECT card_key, permission_level, expires_at, is_used, used_by 
        FROM card_keys 
        WHERE card_key = ?
    `;

    db.get(query, [cardKey], (err, row) => {
        if (err) {
            console.error('数据库查询错误:', err);
            return res.status(500).json({
                success: false,
                message: '服务器内部错误'
            });
        }

        if (!row) {
            return res.json({
                isValid: false,
                expiresAt: 0,
                permissionLevel: 0,
                message: '卡密不存在'
            });
        }

        const now = moment().unix();
        
        if (row.expires_at < now) {
            return res.json({
                isValid: false,
                expiresAt: row.expires_at,
                permissionLevel: 0,
                message: '卡密已过期'
            });
        }

        if (row.is_used && row.used_by !== deviceId) {
            return res.json({
                isValid: false,
                expiresAt: row.expires_at,
                permissionLevel: 0,
                message: '卡密已被其他设备使用'
            });
        }

        // 更新使用状态
        if (!row.is_used) {
            db.run(
                'UPDATE card_keys SET is_used = TRUE, used_by = ?, used_at = ? WHERE card_key = ?',
                [deviceId, now, cardKey]
            );
        }

        // 记录使用日志
        db.run(
            'INSERT INTO usage_logs (card_key, device_id, action) VALUES (?, ?, ?)',
            [cardKey, deviceId, 'verify']
        );

        res.json({
            isValid: true,
            expiresAt: row.expires_at,
            permissionLevel: row.permission_level,
            message: '验证成功'
        });
    });
});

// 获取应用列表（模拟）
app.get('/api/apps', (req, res) => {
    const mockApps = [
        { name: '微信', packageName: 'com.tencent.mm', version: '8.0.0' },
        { name: 'QQ', packageName: 'com.tencent.mobileqq', version: '9.0.0' },
        { name: '支付宝', packageName: 'com.eg.android.AlipayGphone', version: '10.5.0' },
        { name: '抖音', packageName: 'com.ss.android.ugc.aweme', version: '25.0.0' },
        { name: '微博', packageName: 'com.sina.weibo', version: '12.0.0' }
    ];
    
    res.json({
        success: true,
        apps: mockApps
    });
});

// 创建分身（模拟）
app.post('/api/clone', (req, res) => {
    const { packageName, cloneName, userId } = req.body;
    
    if (!packageName || !cloneName) {
        return res.status(400).json({
            success: false,
            message: '缺少必要参数'
        });
    }

    // 模拟创建分身
    const clonePackageName = `${packageName}.clone.${userId || 0}`;
    
    res.json({
        success: true,
        clonePackageName: clonePackageName,
        message: '分身创建成功'
    });
});

// 健康检查
app.get('/api/health', (req, res) => {
    res.json({ status: 'ok', timestamp: moment().unix() });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
    console.log('测试卡密:');
    console.log('TEST-2024-001 - 30天权限');
    console.log('TEST-2024-002 - 90天权限');
    console.log('TEST-2024-003 - 365天权限');
});

// 优雅关闭
process.on('SIGINT', () => {
    console.log('正在关闭服务器...');
    db.close((err) => {
        if (err) {
            console.error('关闭数据库时出错:', err);
        } else {
            console.log('数据库连接已关闭');
        }
        process.exit(0);
    });
});
